package org.softmed.rest.server.test.creators.testcases.parameters;

import org.restlet.data.Response;
import org.restlet.data.Status;
import org.softmed.rest.server.test.creators.AbstractTestCaseCreator;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class DeleteField extends AbstractTestCaseCreator {

	String fieldName;
	private String rootNodeName;
	boolean isSuposedToSuceed = true;

	public DeleteField(String rootNodeName, String fieldName) {
		this.fieldName = fieldName;
		this.rootNodeName = rootNodeName;
	}

	public DeleteField(String rootNodeName, String fieldName, boolean toSuceed) {
		this.fieldName = fieldName;
		this.rootNodeName = rootNodeName;
		this.isSuposedToSuceed = toSuceed;
	}

	@Override
	public String testCase(String uri, String elementURI) throws Throwable {

		Response response = creator.delete(elementURI + "/" + fieldName);
		if (isSuposedToSuceed) {
			if (!response.getStatus().equals(Status.SUCCESS_OK))
				return elementURI;
		} else {
			if (response.getStatus()
					.equals(Status.SERVER_ERROR_NOT_IMPLEMENTED))
				creator.getTestCase().setSucess(true);
			return elementURI;
		}

		setupXMLDoc();

		if (!doc.getDocumentElement().getNodeName().equals(rootNodeName))
			return elementURI;

		NamedNodeMap att = doc.getDocumentElement().getAttributes();

		if (att == null)
			return elementURI;

		Node node = att.getNamedItem("uri");
		if (node == null)
			return elementURI;

		String value = node.getNodeValue();
		if (value == null)
			return elementURI;

		node = att.getNamedItem("name");
		if (node != null)
			return elementURI;

		creator.getTestCase().setSucess(true);

		return elementURI;
	}

	public boolean isSuposedToSuceed() {
		return isSuposedToSuceed;
	}

	public void setSuposedToSuceed(boolean isSuposedToSuceed) {
		this.isSuposedToSuceed = isSuposedToSuceed;
	}

}
